<template>
  <div class="home">
    <div class="header">
      <div class="logo"></div>
      <div class="titleMain">
        <h1>CGL1870镀锌炉温动态控制模型</h1>
      </div>
    </div>
    <el-col class="main-container">
      <el-row :gutter="24" style="height: 28vh">
        <el-col :span="10">
          <div>
            <div class="msg-title">重要信息提示</div>
            <div class="information">
              <div>
                <span class="alarm-row-one-line marquee-text">
                  {{ warningInfo }}
                </span>
              </div>
              <!-- <el-carousel autoplay class="h-100% w-100%" direction="vertical" :interval="3000" indicator-position="none">
                <span style="color: transparent !important">{{ warningInfo }}</span>
                <el-carousel-item v-for="item in warningInfo" :key="item" style="color: white">{{ item.value }}</el-carousel-item>
              </el-carousel> -->
            </div>
            <div :class="viewportWidth == 1920 ? 'p-tem-100' : 'p-tem-125'">
              <div class="key-value-div">
                <span class="temp-key">P4 ： </span><span class="temp-value">{{ ptem.p4temp }} </span>
              </div>
              <div class="key-value-div">
                <span class="temp-key">P5 ： </span><span class="temp-value">{{ ptem.p5temp }} </span>
              </div>
              <div class="key-value-div">
                <span class="temp-key">P6 ： </span><span class="temp-value">{{ ptem.p6temp }} </span>
              </div>
              <div class="key-value-div">
                <span class="temp-key">焊缝距入炉距离 ： </span><span class="temp-value">{{ ptem.distance }} </span>
              </div>
            </div>
            <!-- <div class="svg-clip-wrapper">
              <div class="svg-clip-inner"> -->
            <div class="svg">
              <svg-load :name="technologicalName" />
            </div>
            <!-- </div>
            </div> -->
            <div :class="viewportWidth === 1920 ? 'dew-point-100' : 'dew-point-125'">
              <!-- <span>{{ dewPoint.chinese }}：</span> -->
              <template v-for="(value, key) in dewPoint" :key="key">
                <div v-if="String(key) !== 'chinese'" class="key-value-div">
                  <span class="temp-key">{{ key }} ： </span><span class="temp-value">{{ value }} </span>
                </div>
              </template>
            </div>
          </div>
        </el-col>
        <el-col :span="14">
          <new-coil-card title="设定信息" class="top-set-info">
            <div class="set-info-card-body" :class="viewportWidth == 1920 ? 'table-cell-class-100' : 'table-cell-class-125'">
              <el-table :data="warningTableData" style="width: 100%" :header-cell-style="{ background: '#2f59af', color: '#fff' }">
                <el-table-column prop="chinese" label width="180px" />
                <el-table-column prop="furnaceTemperature12" label="炉温1&2">
                  <template #default="scope">
                    <span v-if="scope.$index === 0">
                      {{ scope.row.furnaceTemperature12 }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="furnaceTemperature34" label="炉温3&4">
                  <template #default="scope">
                    <span v-if="scope.$index === 0">
                      {{ scope.row.furnaceTemperature34 }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="furnaceTemperature56" label="炉温5&6">
                  <template #default="scope">
                    <span v-if="scope.$index === 0">
                      {{ scope.row.furnaceTemperature56 }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="furnaceTemperature7" label="炉温7">
                  <template #default="scope">
                    <span v-if="scope.$index === 0">
                      {{ scope.row.furnaceTemperature7 }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="slowCool" label="缓冷">
                  <template #default="scope">
                    <span v-if="scope.$index === 0">
                      {{ scope.row.slowCool }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="steelType" label="钢种">
                  <template #default="scope">
                    <span v-if="scope.$index === 0">
                      {{ scope.row.steelType }}
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </new-coil-card>
        </el-col>
        <!-- <el-col :span="6">
          <new-coil-card title="各炉段分区" class="top-set-info">
            <div class="set-info-card-body" :class="viewportWidth == 1920 ? 'table-cell-class-100' : 'table-cell-class-125'">
              <el-table
                :data="furnaceSectionTableData"
                :span-method="objectSpanMethod"
                style="width: 100%"
                :header-cell-style="{ background: '#2f59af', color: '#fff' }"
                :show-header="false"
              >
                <el-table-column prop="heat" label="heat" />
                <el-table-column prop="key" label="功能" />
                <el-table-column prop="value" label="值">
                  <template #default="scope">
                    <span v-if="scope.$index === 0 || scope.$index === 2 || scope.$index === 4 || scope.$index === 6">
                      <img :src="imagePath(scope.row.value)" />
                    </span>
                    <span v-else>{{ scope.row.value + '%' }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </new-coil-card>
        </el-col> -->
      </el-row>
      <el-row :gutter="24" style="height: 30vh">
        <el-col :span="18">
          <new-coil-card :title="annealGraphTitle">
            <template #header-right>
              <el-select v-model="annealGraphOption" placeholder="请选择" @change="annealHandleOptionChange()" label="炉区" size="small">
                <el-option v-for="item in annealGraphOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
            <graph-anneal
              :graph-data-upper="upperGraph.toArray()"
              :graph-data-anneal="dataY.toArray()"
              :graph-data-next="dataNext.toArray()"
              :graph-data-lower="lowerGraph.toArray()"
              :xdata="dataTimeX.toArray()"
              :change="graphOptions[annealGraphOption].changeRef.value"
            />
          </new-coil-card>
        </el-col>
        <el-col :span="6">
          <new-coil-card title="基本信息" :class="viewportWidth == 1920 ? '' : 'base-info-125'">
            <el-table :data="baseInfoTableData" style="width: 100%" :header-cell-style="{ background: '#2f59af', color: '#fff' }" size="small">
              <el-table-column prop="基本信息" label="基本信息" />
              <el-table-column prop="currentCoil" label="当前卷">
                <template #default="scope">
                  <span v-if="scope.$index === 4">
                    <img :src="imagePath(scope.row.currentCoil)" />
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="nextCoil" label="下一卷">
                <template #default="scope">
                  <span v-if="scope.$index === 4">
                    <img :src="imagePath(scope.row.nextCoil)" />
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </new-coil-card>
        </el-col>
      </el-row>
      <el-row style="height: 30vh; margin-top: 1vh">
        <el-col :span="24">
          <new-coil-card title="实时温度曲线">
            <template #header-right>
              <el-select v-model="temGraphOption" placeholder="请选择" @change="handleOptionChange()" label="炉区" class="" size="small">
                <el-option v-for="item in temGraphOptions" :key="item.value" :label="item.label" :value="item" />
              </el-select>
            </template>
            <graph-card
              :graph-data-a-i="graphDataAI.toArray()"
              :graph-data-m-m="graphDataMM.toArray()"
              :graph-data-p-l-c="graphDataPLC.toArray()"
              :xdata="realTempTimeX.toArray()"
            />
          </new-coil-card>
        </el-col>
      </el-row>
      <el-row style="height: 13vh; margin-top: 1vh">
        <el-col :span="24">
          <new-coil-card title="AI模型投用状态">
            <el-table :data="aiModeTableData" style="width: 100%" :header-cell-style="{ background: '#2f59af', color: '#fff' }" size="small">
              <el-table-column prop="furnaceTemperature12" label="炉温1&2" align="center">
                <template #default="scope">
                  <span v-if="scope.$index === 0">
                    <img :src="imagePath(scope.row.furnaceTemperature12)" />
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="furnaceTemperature34" label="炉温3&4" align="center">
                <template #default="scope">
                  <span v-if="scope.$index === 0">
                    <img :src="imagePath(scope.row.furnaceTemperature34)" />
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="furnaceTemperature56" label="炉温5&6" align="center">
                <template #default="scope">
                  <span v-if="scope.$index === 0">
                    <img :src="imagePath(scope.row.furnaceTemperature56)" />
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="furnaceTemperature7" label="炉温7" align="center">
                <template #default="scope">
                  <span v-if="scope.$index === 0">
                    <img :src="imagePath(scope.row.furnaceTemperature7)" />
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="slowCool" label="缓冷" align="center">
                <template #default="scope">
                  <span v-if="scope.$index === 0">
                    <img :src="imagePath(scope.row.slowCool)" />
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </new-coil-card>
        </el-col>
      </el-row>
    </el-col>
  </div>
</template>
<script lang="ts" setup>
  import NewCoilCard from '/@/components/NewCoilCard/NewCoilCard.vue';
  import { ref, onMounted, onUnmounted, onBeforeMount } from 'vue';
  import GraphCard from '/@/components/CpcWidth/GraphCard.vue';
  import GraphAnneal from '/@/components/GraphDraw/GraphAnneal.vue';
  import dayjs from 'dayjs';
  import { furnaceTempDynamicCtrlApi } from '/@/api/furnaceTempDynamicCtrl/index';
  import { ElMessage } from 'element-plus';
  import { refreshSVG, initialSVG, refreshGraphical } from '/@/common/refreshSVG';
  import { rollingSimulationApi } from '/@/api/RollingSimulation/index';
  import { useUserStore } from '/@/store/modules/system/user';
  import CircularDeque from './deque';

  // 格式化数值
  const formatNum = (value: any) => {
    if (value == null || isNaN(value)) return '0.00';
    const num = Number(value);
    return num.toFixed(2);
  };

  const baseInfoTableData = ref([
    { 基本信息: '钢卷号', currentCoil: '', nextCoil: '' },
    { 基本信息: '钢种', currentCoil: '', nextCoil: '' },
    { 基本信息: '宽度', currentCoil: '', nextCoil: '' },
    { 基本信息: '厚度', currentCoil: '', nextCoil: '' },
    { 基本信息: '反射率异常', currentCoil: '', nextCoil: '' },
  ]);

  const furnaceSectionTableData = ref([
    { heat: 'heat1&2', key: '供热能力', value: '' },
    { heat: 'heat1&2', key: '辐射管使用率', value: '' },
    { heat: 'heat3&4', key: '供热能力', value: '' },
    { heat: 'heat3&4', key: '辐射管使用率', value: '' },
    { heat: 'heat5&6', key: '供热能力', value: '' },
    { heat: 'heat5&6', key: '辐射管使用率', value: '' },
    { heat: 'heat7', key: '供热能力', value: '' },
    { heat: 'heat7', key: '辐射管使用率', value: '' },
  ]);

  const objectSpanMethod = ({ rowIndex, columnIndex }: { rowIndex: number; columnIndex: number }) => {
    if (columnIndex === 0) {
      // 使用模运算来简化条件判断
      if (rowIndex % 2 === 0) {
        return { rowspan: 2, colspan: 1 };
      } else {
        return { rowspan: 0, colspan: 0 };
      }
    }
    // 对于其他列，不需要合并单元格，可以返回 null 或 undefined
    return null;
  };
  let tr: any = null;
  let por: any = null;
  let ti: any = null;

  // 图表数据量上限
  const MAX_DATA_POINTS = 300;
  const viewportWidth = ref();
  const viewportHeight = ref();
  const graphDataAI = ref(new CircularDeque<any>(MAX_DATA_POINTS));
  const graphDataMM = ref(new CircularDeque<any>(MAX_DATA_POINTS));
  const graphDataPLC = ref(new CircularDeque<any>(MAX_DATA_POINTS));
  const setInfoTableRef = ref();
  const exportLooper = ref<number>(0);

  // --- 生命周期钩子 ---
  let interval: any = null;

  const dataY = ref(new CircularDeque<any>(MAX_DATA_POINTS)); //退火曲线数据
  const dataNext = ref(new CircularDeque<any>(MAX_DATA_POINTS)); //退火曲线数据（切卷用）
  const p4Change = ref(0); //退火曲线切卷判定用
  const p5Change = ref(0); //退火曲线切卷判定用
  const p6Change = ref(0); //退火曲线切卷判定用
  const beforeChange = ref<number>(0); //退火曲线切卷判定用(上一个炉子)
  const currentId = ref(''); // 当前卷号
  const dataTimeX = ref(new CircularDeque<any>(MAX_DATA_POINTS)); // 退火曲线时间轴数据
  const realTempTimeX = ref(new CircularDeque<any>(MAX_DATA_POINTS)); // 实时温度曲线时间轴数据
  const lowerGraph = ref(new CircularDeque<any>(MAX_DATA_POINTS)); // 退火曲线下限数据
  const upperGraph = ref(new CircularDeque<any>(MAX_DATA_POINTS)); // 退火曲线上限数据
  const technologicalName = 'combinedCAGalvTempModels'; // 工艺名称 CGL1870镀锌
  const inletLooper = ref<number>(0); // 钢卷跟踪用变量
  const middleLooper = ref<number>(0); // 钢卷跟踪用变量
  const aiModeTableData = ref([
    {
      furnaceTemperature12: 0,
      furnaceTemperature34: 0,
      furnaceTemperature56: 0,
      furnaceTemperature7: 0,
      slowCool: 0,
    },
  ]);

  type Options = {
    value: number;
    label: string;
  };

  // 定义图表选项接口
  interface AnnealGraphOption {
    value: number;
    label: string;
    topTag: string; // 顶部曲线标签
    middleTag: string; // 中间温度标签
    bottomTag: string; // 底部曲线标签
    changeRef: Ref<number>; // 变化状态引用
  }

  // 定义图表选项配置
  const graphOptions: AnnealGraphOption[] = [
    {
      value: 0,
      label: 'P4',
      topTag: 'p4_linetop',
      middleTag: 'cal_heat_strip_temp',
      bottomTag: 'p4_linebtm',
      changeRef: p4Change,
    },
    {
      value: 1,
      label: 'P5',
      topTag: 'p5_linetop',
      middleTag: 'cal_soak_strip_temp',
      bottomTag: 'p5_linebtm',
      changeRef: p5Change,
    },
    {
      value: 2,
      label: 'P6',
      topTag: 'p6_linetop',
      middleTag: 'cal_sc_strip_temp',
      bottomTag: 'p6_linebtm',
      changeRef: p6Change,
    },
  ];

  // 定义警告表格数据接口
  interface WarningTableData {
    chinese: string;
    furnaceTemperature12: string;
    furnaceTemperature34: string;
    furnaceTemperature56: string;
    furnaceTemperature7: string;
    slowCool: string;
    steelType: string;
  }

  const warningTableData = ref<WarningTableData[]>([
    {
      chinese: '工艺过度异常提示',
      furnaceTemperature12: '-',
      furnaceTemperature34: '-',
      furnaceTemperature56: '-',
      furnaceTemperature7: '-',
      slowCool: '-',
      steelType: '-',
    },
    {
      chinese: '当前卷AI模型设定值',
      furnaceTemperature12: '',
      furnaceTemperature34: '',
      furnaceTemperature56: '',
      furnaceTemperature7: '',
      slowCool: '',
      steelType: '',
    },
    {
      chinese: '下一卷AI模型设定值',
      furnaceTemperature12: '',
      furnaceTemperature34: '',
      furnaceTemperature56: '',
      furnaceTemperature7: '',
      slowCool: '',
      steelType: '',
    },
    {
      chinese: '实际值',
      furnaceTemperature12: '',
      furnaceTemperature34: '',
      furnaceTemperature56: '',
      furnaceTemperature7: '',
      slowCool: '',
      steelType: '',
    },
    {
      chinese: '供热能力',
      furnaceTemperature12: '',
      furnaceTemperature34: '',
      furnaceTemperature56: '',
      furnaceTemperature7: '',
      slowCool: '',
      steelType: '',
    },
    {
      chinese: '辐射管使用率',
      furnaceTemperature12: '',
      furnaceTemperature34: '',
      furnaceTemperature56: '',
      furnaceTemperature7: '',
      slowCool: '',
      steelType: '',
    },
  ]);

  // 下拉框选项
  const temGraphOptions = ref([
    { value: 0, label: '炉温1&2' },
    { value: 1, label: '炉温3&4' },
    { value: 2, label: '炉温5&6' },
    { value: 3, label: '炉温7' },
  ]);

  // 下拉框选项
  const annealGraphOptions = ref([
    { value: 0, label: 'P4' },
    { value: 1, label: 'P5' },
    { value: 2, label: 'P6' },
  ]);
  const temGraphOption = ref<Options>({ value: 0, label: '炉温1&2' });
  const annealGraphOption = ref<number>(0);
  const annealGraphTitle = ref('P3与退火曲线实时对比');

  interface PTEM {
    p4temp: string;
    p5temp: string;
    p6temp: string;
    distance: string;
  }

  // 各个炉温实时值
  const ptem = ref<PTEM>({
    p4temp: '0',
    p5temp: '0',
    p6temp: '0',
    distance: '0',
  });

  // 警告信息
  const warningInfo = ref('');

  // 露点数据
  const dewPoint = ref<any>({
    chinese: '露点',
    Phtg: '0',
    Htg1: '0',
    Htg2: '0',
    Soak: '0',
    SCZ1: '0',
    SCZ2: '0',
    RCZ1: '0',
    RCZ2: '0',
    RCZ3: '0',
    Equal: '0',
  });

  // 正常（0）/ 异常 （1）判定
  const imagePath = (value: number) => {
    let name = 'red.png';
    if (value == 0) {
      name = 'green.png';
    }
    return `/src/assets/images/${name}`;
  };

  // 实时温度曲线图表切换
  const handleOptionChange = () => {
    graphDataAI.value.clear();
    graphDataMM.value.clear();
    graphDataPLC.value.clear();
    realTempTimeX.value.clear();
    p4Change.value = 0;
    p5Change.value = 0;
    p6Change.value = 0;
  };

  // 退火曲线切换
  const annealHandleOptionChange = async () => {
    upperGraph.value.clear();
    lowerGraph.value.clear();
    dataY.value.clear();
    dataNext.value.clear();
    dataTimeX.value.clear();
    currentId.value = '';
    annealGraphTitle.value = `${annealGraphOptions.value[annealGraphOption.value].label}与退火曲线实时对比`;

    const changeRefsMap: { [key: number]: Ref<number> } = {
      0: p4Change,
      1: p5Change,
      2: p6Change,
    };

    // 获取当前选中的值
    const currentValue = annealGraphOption.value;
    const judgeValue = changeRefsMap[beforeChange.value].value;

    // 重置所有卷判定值为0
    Object.values(changeRefsMap).forEach((ref) => {
      ref.value = 0;
    });

    if (judgeValue) {
      changeRefsMap[currentValue].value = judgeValue;
    }
    beforeChange.value = currentValue;
  };

  // 钢卷跟踪
  async function getZoneTrk() {
    let param = {
      name: 'CGL1870_zonetrk',
    };
    rollingSimulationApi.rest(param).then((res) => {
      let zones = res.data.zoneno;
      if (currentId.value == '') {
        annealGraphOption.value == 0
          ? (currentId.value = zones[82].entId)
          : annealGraphOption.value == 1
          ? (currentId.value = zones[87].entId)
          : (currentId.value = zones[95].entId);
      }
      if (annealGraphOption.value == 0 && zones[40].entId != currentId.value) {
        currentId.value = zones[40].entId;
        p4Change.value += 1;
      } else if (annealGraphOption.value == 1 && zones[43].entId != currentId.value) {
        currentId.value = zones[43].entId;
        p5Change.value += 1;
      } else if (annealGraphOption.value == 2 && zones[45].entId != currentId.value) {
        currentId.value = zones[45].entId;
        p6Change.value += 1;
      }
      inletLooper.value = res.data['loop'][0];
      middleLooper.value = res.data['loop'][1];
      exportLooper.value = res.data['loop'][2];

      let trKey = `${technologicalName}-ZONE_tr${res.data.tr}`;
      let trpathKey = trKey + '_path';
      let porKey = `${technologicalName}-ZONE_por${res.data.por}`;
      let porpathKey = porKey + '_path';
      var arr = Object.keys(zones);
      /**开卷机和卷取机 */
      if (tr === null || tr !== res.data.tr) {
        tr = res.data.tr;
        refreshSVG(zones[arr.length - 1].ti % 10, trpathKey);
        refreshGraphical(zones[arr.length - 1].ti % 10, trKey);
        initialSVG(technologicalName, 'tr', res.data.tr);
      }
      if (por === null || por !== res.data.por) {
        por = res.data.por;
        if (res.data.por === 0) {
          initialSVG(technologicalName, 'por', '1');
          initialSVG(technologicalName, 'por', '2');
        }
      }
      if (ti === null || ti !== zones[0].ti) {
        ti = zones[0].ti;
        refreshSVG(zones[0].ti % 10, porpathKey);
        refreshGraphical(zones[0].ti % 10, porKey);
        initialSVG(technologicalName, 'por', res.data.por);
      }
      for (let i in zones) {
        let pathkey = `${technologicalName}-ZONE${i}`;
        refreshSVG(zones[i].ti % 10, pathkey);
      }
    });
  }

  // 获取露点数据
  async function getDewPointData() {
    const param = {
      name: 'CGL1870_RealData',
    };

    try {
      const res = await furnaceTempDynamicCtrlApi.getDewPointData(param);

      if (res?.data) {
        const { data } = res;
        if (data.DB40_DBD840) dewPoint.value.Phtg = formatNum(data.DB40_DBD840);
        if (data.DB40_DBD844) dewPoint.value.Htg1 = formatNum(data.DB40_DBD844);
        if (data.DB40_DBD848) dewPoint.value.Htg2 = formatNum(data.DB40_DBD848);
        if (data.DB40_DBD852) dewPoint.value.Soak = formatNum(data.DB40_DBD852);
        if (data.DB40_DBD856) dewPoint.value.SCZ1 = formatNum(data.DB40_DBD856);
        if (data.DB40_DBD860) dewPoint.value.SCZ2 = formatNum(data.DB40_DBD860);
        if (data.DB40_DBD864) dewPoint.value.RCZ1 = formatNum(data.DB40_DBD864);
        if (data.DB40_DBD868) dewPoint.value.RCZ2 = formatNum(data.DB40_DBD868);
        if (data.DB40_DBD872) dewPoint.value.RCZ3 = formatNum(data.DB40_DBD872);
        if (data.DB40_DBD876) dewPoint.value.Equal = formatNum(data.DB40_DBD876);
      }
    } catch (error) {
      const errorInfo = {
        message: '获取露点数据失败',
        error: error instanceof Error ? error.message : String(error),
        params: param,
        timestamp: new Date().toISOString(),
        stack: error instanceof Error ? error.stack : undefined,
      };
      console.error('API Error:', errorInfo);
      throw new Error(`获取露点数据失败: ${errorInfo.error}`);
    }
  }

  const fetchData = () => {
    try {
      interval = setInterval(() => {
        getZoneTrk();
        getHMI();
        // getCurCoilAISet();
        getDewPointData();
        dataTimeX.value.push(dayjs().format('HH:mm:ss'));
        realTempTimeX.value.push(dayjs().format('HH:mm:ss'));
      }, 2000);
    } catch (error) {
      const errorInfo = {
        message: '定时获取数据失败',
        error: error instanceof Error ? error.message : String(error),
        timestamp: new Date().toISOString(),
      };
      console.error('Interval Error:', errorInfo);
      ElMessage.error(`获取数据失败: ${errorInfo.error}`);
    }
  };

  // 获取页面数据
  const getHMI = async () => {
    try {
      const tagGroups = {
        // 炉温
        furnaceTemps: ['cgl_p4_temp_act', 'cgl_p5_temp_act', 'cgl_p6_temp_act'],
        // 当前卷AI设定初始值
        // currentCoilAIStart: ['FURT_12_AI', 'FURT_34_AI', 'FURT_56_AI', 'FURT_78_AI', 'FURT_910_AI', 'FURT_1112_AI', 'FURT_13_AI', 'FURT_14_AI'],
        // 当前卷AI设定值
        currentCoilAISet: ['FURT_12', 'FURT_34', 'FURT_56', 'FURT_7', 'SLOWCOOL', 'STEELTP'],
        // 下一卷AI设定值
        nextCoilAISet: ['FURT_12NXT', 'FURT_34NXT', 'FURT_56NXT', 'FURT_7NXT', 'SLOWCOOLNXT', 'STEELTPNXT'],
        // 实际值
        actualValues: ['cgl_heat_hs12_temp', 'cgl_heat_hs34_temp', 'cgl_heat_hs56_temp', 'cgl_hs7_temp_act'],
        // 供热能力
        heatCapacities: ['gr12', 'gr34', 'gr56', 'gr7'],
        // 辐射管使用率
        tubeUsageRates: ['sz12', 'sz34', 'sz56', 'sz7'],
        // 基本信息
        baseInfos: ['coilid', 'STEELTP', 'width', 'thick', 'fslv', 'coilidnxt', 'STEELTPNXT', 'widthnxt', 'thicknxt', 'fslvnxt'],
        // 退火曲线
        annealCurves: ['cgl_p4_temp_set', 'cgl_p5_temp_set', 'cgl_p6_temp_set'],
        // 实时温度曲线
        realtimeCurves: ['cgl_heat_12', 'cgl_heat_34', 'cgl_heat_56', 'cgl_heat_7'],
        // AI模型投用状态
        aiModes: [
          'GAL_DATA.ControlModeHS12',
          'GAL_DATA.ControlModeHS34',
          'GAL_DATA.ControlModeHS56',
          'GAL_DATA.ControlModeHS7',
          'GAL_DATA.ControlModeSCS',
        ],
        // 其他单独标签
        others: ['WELD_TO_FUR', 'result'],
      };
      const tagNames = [
        ...tagGroups.furnaceTemps,
        // ...tagGroups.currentCoilAIStart,
        ...tagGroups.currentCoilAISet,
        ...tagGroups.nextCoilAISet,
        ...tagGroups.actualValues,
        ...tagGroups.heatCapacities,
        ...tagGroups.tubeUsageRates,
        ...tagGroups.baseInfos,
        ...tagGroups.annealCurves,
        ...tagGroups.realtimeCurves,
        ...tagGroups.aiModes,
        ...tagGroups.others,
      ];

      // 构造请求参数
      const param = {
        action: 'get_tags',
        operator: 'abc',
        terminal: 'FM_01',
        body: tagNames.map((tagName) => ({ tagName: tagName, timestamp: 0 })),
      };

      const res = await furnaceTempDynamicCtrlApi.getTableData(param);
      const tagValueMap = res.data.results.reduce((map: any, item: any) => {
        map[item.tagName] = item.value;
        return map;
      }, {});

      //  赋值：实时炉温
      console.log(tagValueMap[tagGroups.others[0]]);
      ptem.value = {
        p4temp: formatNum(tagValueMap[tagGroups.furnaceTemps[0]]),
        p5temp: formatNum(tagValueMap[tagGroups.furnaceTemps[1]]),
        p6temp: formatNum(tagValueMap[tagGroups.furnaceTemps[2]]),
        distance: tagValueMap[tagGroups.others[0]], // 焊缝距离
      };

      // TODO 警告信息
      // warningInfo.value = tagValueMap[tagGroups.others[1]]
      //   .replace('STEELGRADE', '牌号')
      //   .replace('AIM', '目标')
      //   .replaceAll(':', ': ')
      //   .replaceAll(',', ', '); // 警告信息

      //赋值：当前卷AI设定初始值
      // const [s12, s34, s56, s7, sslowCool, ssteelType] = tagGroups.currentCoilAIStart.map((tag) => formatNum(tagValueMap[tag]));
      // warningTableData.value[0] = {
      //   chinese: '当前卷AI设定初始值',
      //   furnaceTemperature12: s12,
      //   furnaceTemperature34: s34,
      //   furnaceTemperature56: s56,
      //   furnaceTemperature7: s7,
      //   slowCool: sslowCool,
      //   steelType: ssteelType,
      // };

      // 赋值：当前卷AI设定值
      const [f12, f34, f56, f7, slowCool, steelType] = tagGroups.currentCoilAISet.map((tag) => tagValueMap[tag]);
      warningTableData.value[1] = {
        chinese: '当前卷AI模型设定值',
        furnaceTemperature12: formatNum(f12),
        furnaceTemperature34: formatNum(f34),
        furnaceTemperature56: formatNum(f56),
        furnaceTemperature7: formatNum(f7),
        slowCool: formatNum(slowCool),
        steelType: steelType,
      };

      // 赋值：下一卷AI设定值
      const [nf12, nf34, nf56, nf7, nSlowCool, nSteelType] = tagGroups.nextCoilAISet.map((tag) => tagValueMap[tag]);
      warningTableData.value[2] = {
        chinese: '下一卷AI模型设定值',
        furnaceTemperature12: formatNum(nf12),
        furnaceTemperature34: formatNum(nf34),
        furnaceTemperature56: formatNum(nf56),
        furnaceTemperature7: formatNum(nf7),
        slowCool: formatNum(nSlowCool),
        steelType: nSteelType,
      };

      // 9. 赋值：实际值
      const [af12, af34, af56, af7] = tagGroups.actualValues.map((tag) => formatNum(tagValueMap[tag]));
      warningTableData.value[3] = {
        chinese: '实际值',
        furnaceTemperature12: af12,
        furnaceTemperature34: af34,
        furnaceTemperature56: af56,
        furnaceTemperature7: af7,
        slowCool: formatNum(tagValueMap[tagGroups.furnaceTemps[2]]),
        steelType: '-',
      };

      //赋值：供热能力
      warningTableData.value[4] = {
        chinese: '供热能力',
        furnaceTemperature12: tagValueMap[tagGroups.heatCapacities[0]],
        furnaceTemperature34: tagValueMap[tagGroups.heatCapacities[1]],
        furnaceTemperature56: tagValueMap[tagGroups.heatCapacities[2]],
        furnaceTemperature7: tagValueMap[tagGroups.heatCapacities[3]],
        slowCool: '-',
        steelType: '-',
      };

      // 赋值：辐射管使用率（对应tubeUsageRates）
      warningTableData.value[5] = {
        chinese: '辐射管使用率',
        furnaceTemperature12: formatNum(tagValueMap[tagGroups.tubeUsageRates[0]]),
        furnaceTemperature34: formatNum(tagValueMap[tagGroups.tubeUsageRates[1]]),
        furnaceTemperature56: formatNum(tagValueMap[tagGroups.tubeUsageRates[2]]),
        furnaceTemperature7: formatNum(tagValueMap[tagGroups.tubeUsageRates[3]]),
        slowCool: '-',
        steelType: '-',
      };

      // 赋值：基本信息（对应baseInfos）
      const [coilid, steelTp, width, thick, fslv, coilidNxt, steelTpNxt, widthNxt, thickNxt, fslvNxt] = tagGroups.baseInfos.map(
        (tag) => tagValueMap[tag]
      );
      baseInfoTableData.value = [
        { 基本信息: '钢卷号', currentCoil: coilid, nextCoil: coilidNxt },
        { 基本信息: '钢种', currentCoil: steelTp, nextCoil: steelTpNxt },
        { 基本信息: '宽度', currentCoil: width, nextCoil: widthNxt },
        { 基本信息: '厚度', currentCoil: thick, nextCoil: thickNxt },
        { 基本信息: '反射率异常', currentCoil: fslv, nextCoil: fslvNxt },
      ];

      // 退火曲线：用配置表替代if-else（对应annealCurves）
      const annealConfig = [
        { option: 0, setIdx: 0, tempIdx: 0, change: p4Change },
        { option: 1, setIdx: 1, tempIdx: 1, change: p5Change },
        { option: 2, setIdx: 2, tempIdx: 2, change: p6Change },
      ];
      const currentAnneal = annealConfig.find((item) => item.option === annealGraphOption.value);
      if (currentAnneal) {
        const { setIdx, tempIdx, change } = currentAnneal;
        const tempSet = tagValueMap[tagGroups.annealCurves[setIdx]];
        lowerGraph.value.push(Number(tempSet) - 10);
        upperGraph.value.push(Number(tempSet) + 10);
        const tempValue = formatNum(tagValueMap[tagGroups.furnaceTemps[tempIdx]]);
        if (change.value % 2 === 1) {
          dataY.value.push(null);
          dataNext.value.push(tempValue);
        } else {
          dataNext.value.push(null);
          dataY.value.push(tempValue);
        }
      }

      // 实时温度曲线：用配置表替代if-else（对应realtimeCurves）
      const tempCurveConfig = [
        { option: 0, mmIdx: 0, aiIdx: 0, plcIdx: 0 },
        { option: 1, mmIdx: 1, aiIdx: 1, plcIdx: 1 },
        { option: 2, mmIdx: 2, aiIdx: 2, plcIdx: 2 },
        { option: 3, mmIdx: 3, aiIdx: 3, plcIdx: 3 },
      ];
      const currentTempCurve = tempCurveConfig.find((item) => item.option === temGraphOption.value.value);
      if (currentTempCurve) {
        const { mmIdx, aiIdx, plcIdx } = currentTempCurve;
        graphDataMM.value.push(formatNum(tagValueMap[tagGroups.realtimeCurves[mmIdx]]));
        graphDataAI.value.push(formatNum(tagValueMap[tagGroups.currentCoilAISet[aiIdx]]));
        graphDataPLC.value.push(formatNum(tagValueMap[tagGroups.actualValues[plcIdx]]));
      }

      // 赋值：AI模型投用状态（对应aiModes）
      aiModeTableData.value[0] = {
        furnaceTemperature12: tagValueMap[tagGroups.aiModes[0]],
        furnaceTemperature34: tagValueMap[tagGroups.aiModes[1]],
        furnaceTemperature56: tagValueMap[tagGroups.aiModes[2]],
        furnaceTemperature7: tagValueMap[tagGroups.aiModes[3]],
        slowCool: tagValueMap[tagGroups.aiModes[4]],
      };
    } catch (error) {
      // 清空图表数据
      [lowerGraph, upperGraph, dataY, dataNext, graphDataMM, graphDataAI, graphDataPLC].forEach((ref) => ref.value.push(null));

      const errorInfo = {
        message: '获取HMI数据失败',
        error: error instanceof Error ? error.message : String(error),
        timestamp: new Date().toISOString(),
      };
      console.error('HMI Error:', errorInfo);
      ElMessage.error(`获取数据失败: ${errorInfo.message}`);
    }
  };

  // 当前卷AI模型设定值
  // const getCurCoilAISet = async () => {
  //   try {
  //     const res = await furnaceTempDynamicCtrlApi.getFurnaceSet();
  //     warningTableData.value[1].furnaceTemperature12 = res.data.furnace12;
  //     warningTableData.value[1].furnaceTemperature34 = res.data.furnace34;
  //     warningTableData.value[1].furnaceTemperature56 = res.data.furnace56;
  //     warningTableData.value[1].furnaceTemperature78 = res.data.furnace78;
  //     warningTableData.value[1].furnaceTemperature910 = res.data.furnace910;
  //     warningTableData.value[1].furnaceTemperature1112 = res.data.furnace1112;
  //     warningTableData.value[1].furnaceTemperature13 = res.data.furnace13;
  //     warningTableData.value[1].furnaceTemperature14 = res.data.furnace14;
  //     warningTableData.value[1].slowCool = res.data.slowCool;
  //   } catch (error: any) {
  //     console.error('error:' + error);
  //   }
  // };

  // 目录数据
  const menuData = ref([
    { menuName: 'CGL1870TempCtrlIndex', menuTitle: 'CGL1870镀锌炉温动态控制模型主页面', menuId: '1' },
    { menuName: 'CGL1870TempCtrlInput', menuTitle: 'CGL1870镀锌离线计算参数输入画面' },
    { menuName: 'CGL1870TempCtrlList', menuTitle: 'CGL1870镀锌离线计算参数列表画面' },
    { menuName: 'CGL1870TempCtrlHistory', menuTitle: 'CGL1870镀锌带钢温度异常分析' },
  ]);
  onBeforeMount(() => {
    useUserStore().setTagNav(menuData.value);
  });

  onMounted(() => {
    fetchData();
    viewportWidth.value = window.innerWidth;
    viewportHeight.value = window.innerHeight;
  });

  onUnmounted(() => {
    dataTimeX.value.clear();
    realTempTimeX.value.clear();
    graphDataAI.value.clear();
    graphDataMM.value.clear();
    graphDataPLC.value.clear();
    dataY.value.clear();
    dataNext.value.clear();
    upperGraph.value.clear();
    lowerGraph.value.clear();
    clearInterval(interval);
  });
</script>
<style lang="less" scoped>
  // ------------------------------  common  ------------------------------------

  .main-container {
    width: 98vw;
    // ---------------------  table ---------------
    :deep(.el-table) {
      background-color: transparent !important;
      --el-table-border: none;
      --el-table-row-hover-bg-color: unset;
      color: white;
    }

    :deep(.el-table th),
    :deep(.el-table tr),
    :deep(.el-table td) {
      background-color: transparent;
    }

    :deep(.el-table__row:nth-child(odd)) {
      background-color: #223671;
    }

    :deep(.el-table__inner-wrapper::before) {
      left: 0;
      bottom: 0;
      width: 100%;
      height: 0;
    }

    // ------------------------------  select  ----------
    :deep(.el-select .el-select__wrapper) {
      background-color: rgba(41, 121, 255, 0.2) !important;
      border: 1px solid #42b4ff !important;
      box-shadow: 0 0 8px rgba(41, 121, 255, 0.5) !important;
      height: 22px !important;
      width: auto !important;
      border-radius: 3px !important;
      transition: border-color 0.2s;
    }
    :deep(.el-select .el-input__inner) {
      height: 20px !important;
      line-height: 20px !important;
      font-size: 14px !important;
      color: #fff !important;
      padding: 0 10px;
      background: transparent !important;
    }
    :deep(.el-select .el-select__caret) {
      font-size: 14px !important;
      color: #42b4ff;
    }
    :deep(.el-select .el-select__placeholder) {
      font-size: 14px !important;
      color: #a0a3a8 !important;
    }
    :deep(.el-select:hover .el-select__selected-item) {
      /* background-color: #42b4ff !important; */
      background-color: transparent !important;
    }

    :deep(.el-select-dropdown) {
      background-color: #142a52 !important;
      border: 1px solid #2a5caa !important;
    }
    :deep(.el-select-dropdown__item) {
      color: #a2cfff !important;
      background-color: #142a52 !important;
    }
    :deep(.el-select-dropdown__item.selected) {
      background-color: #1890ff !important;
      color: #fff !important;
    }
    :deep(.el-select-dropdown__item.hover) {
      background-color: #1e3a6d !important;
      color: #fff !important;
    }
  }

  // ------------------------------   top   ------------------------------------

  .msg-title {
    margin-top: -6vh;
    // left: 39.5vw;
    background-image: -webkit-linear-gradient(left, #0072ff, #00eaff, #01aaff);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    font-size: 2vh;
    font-weight: bolder;
    // width: 10vw;
  }

  .information {
    height: 3.5vh;
    width: 100%;
    display: inline-block;
    white-space: nowrap;
    overflow: hidden;
    color: #fff;
    border: 2px solid #3981d9;
    border-radius: 5px;
    padding: 0 0.2vw;
    display: flex;
    align-items: center;
    margin-bottom: 1vh;
  }

  .alarm-row-one-line.ellipsis {
    display: inline-block;
    max-width: 520px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
    cursor: pointer;
    margin-top: 8px;
  }

  .marquee-text {
    display: inline-block;
    white-space: nowrap;
    animation: marquee 18s linear infinite;
    font-size: 15px;
    font-weight: 500;
    padding-left: 10px;
  }
  @keyframes marquee {
    0% {
      transform: translateX(100%);
    }
    100% {
      transform: translateX(-100%);
    }
  }

  .top-set-info {
    width: 100%;
    height: 100%;
    margin-top: -3vh;

    .set-info-card-body {
      width: 100%;
      height: 100%;
    }
  }

  .table-cell-class-125 {
    :deep(.el-table) {
      .el-table__cell {
        padding: 2px 2px !important; // 横向纵向同时压缩
        .cell {
          height: auto !important;
          line-height: 1.8;
          font-size: 10px !important;
          transform: scale(0.85); // 字体缩放
          transform-origin: left; // 防止内容偏移
          white-space: nowrap; // 禁止换行
          // overflow: hidden;
          text-overflow: ellipsis; // 溢出显示...
        }
      }
    }
  }

  .table-cell-class-100 {
    :deep(.el-table) {
      .el-table__cell {
        padding: 2px 4px !important; // 横向纵向同时压缩
        .cell {
          height: auto !important;
          line-height: 1.9;
          font-size: 12px !important;
          transform: scale(0.85); // 字体缩放
          transform-origin: left; // 防止内容偏移
          white-space: nowrap; // 禁止换行
          // overflow: hidden;
          text-overflow: ellipsis; // 溢出显示...
        }
      }
    }
  }

  .p-tem-125,
  .p-tem-100,
  .dew-point-100,
  .dew-point-125 {
    width: 100%;
    color: #fff;
    display: flex;
    flex-wrap: nowrap;
    font-size: 8px;
    justify-content: space-around;

    .key-value-div {
      padding: 1px 4px;
      background-color: rgba(0, 100, 200, 0.2);
      border-radius: 3px;
      box-shadow: 0 4px 16px rgba(255, 255, 255, 0.08);
      transition: all 0.3s ease;
      cursor: pointer; // 添加指针样式
      display: flex;
      flex-wrap: wrap; /* 允许内部元素（键、值）换行 */
      align-items: center; /* 键和值垂直居中对齐 */
      justify-content: center;

      // 悬停状态
      &:hover {
        box-shadow: 0 8px 32px rgba(255, 255, 255, 0.12);
        transform: translateY(-2px); // 添加上浮效果
        background: lighten(#063e90, 10%); // 背景色变亮
        border-color: lighten(#dcdfe6, 20%); // 边框变亮
      }
    }

    .temp-value {
      color: #f6e085;
      word-break: break-all; /* 内容过长时，强制换行（避免单个长字符撑破容器） */
      margin-left: 2px; /* 与“键”保持微小间距 */
    }
    .temp-key {
      color: #fff;
    }
  }

  .p-tem-125,
  .dew-point-125 {
    font-size: 8px;
    flex-shrink: 0;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 3px;
  }

  .p-tem-100,
  .dew-point-100 {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 4px;
    font-size: 11px;
    flex-shrink: 0;
  }

  .svg {
    width: 100%;
    height: 20vh;
    flex-shrink: 0;

    svg {
      width: 100%;
      height: 100%;
    }
  }

  // ------------------------------   middle   ----------
  .base-info-125 {
    :deep(.el-table) {
      .el-table__cell {
        padding: 2px 4px !important; // 横向纵向同时压缩
        .cell {
          height: auto !important;
          line-height: 2;
          font-size: 12px !important;
          transform: scale(0.85); // 字体缩放
          transform-origin: left; // 防止内容偏移
          white-space: nowrap; // 禁止换行
          text-overflow: ellipsis; // 溢出显示...
        }
      }
    }
  }
</style>
